package com.hmdp.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.common.constant.RedisConstants;
import com.hmdp.core.service.ISeckillVoucherService;
import com.hmdp.entity.db.SeckillVoucher;
import com.hmdp.entity.db.VoucherOrder;
import com.hmdp.core.mapper.VoucherOrderMapper;
import com.hmdp.core.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.dto.Result;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @PostConstruct
    public void initRedis() {
        log.info("初始化秒杀卷库存数据缓存start");
        List<SeckillVoucher> seckillVouchers = seckillVoucherService.list(new LambdaQueryWrapper<>(null));
        if(seckillVouchers.isEmpty()) {
            log.info("初始化秒杀卷库存数据缓存end");
            return;
        }
        seckillVouchers.forEach(f -> {
            Long voucherId = f.getVoucherId();
            Integer stock = f.getStock();
            String key = RedisConstants.SECKILL_STOCK_KEY + voucherId;
            stringRedisTemplate.opsForValue().set(key,stock.toString());
        });
        log.info("初始化秒杀卷库存数据缓存end");

        log.info("初始化秒杀卷订单数据缓存start");
        List<Long> voucherIdList = seckillVouchers.stream().map(SeckillVoucher::getVoucherId).collect(Collectors.toList());
        List<VoucherOrder> voucherOrderList = this.lambdaQuery().in(VoucherOrder::getVoucherId, voucherIdList).list();
        Map<Long, List<VoucherOrder>> map = voucherOrderList.stream().collect(Collectors.groupingBy(VoucherOrder::getVoucherId));
        map.forEach((k,v) -> {
            String key = RedisConstants.SECKILL_ORDER_KEY + k;
            stringRedisTemplate.delete(key);
            stringRedisTemplate.opsForSet().add(key, v.stream().map(m -> m.getUserId().toString()).toArray(String[]::new));
        });
        log.info("初始化秒杀卷订单数据缓存end");
    }

    /**
     * 基于redis锁的秒杀
     *
     * 1. 主逻辑
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.查询优惠卷
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        if(voucher == null) {
            return Result.fail("不存在");
        }

        //2.判断是否开始
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚未开始!");
        }

        //3.判断是否结束
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束！");
        }

        //4.判断库存
        if (voucher.getStock() < 1) {
            return Result.fail("库存不足！");
        }

        Long userId = UserHolder.getUser().getId();
        /*
            toString实际上是new了一个String对象，因此不能作为唯一标识，而加了intern()后，
            获取字符串池里找内容的一样的地址值并返回，保证了唯一
         */
        /*
            在这里上锁是因为：
            如果在方法里上锁的的话，方法内那一部分执行完毕后就会释放锁，
            然后Spring提交事务，导致并发不安全
            而在调用方法上上锁，就可以让Spring先提交事务，再释放锁，提升安全性
         */
//        synchronized (userId.toString().intern()) {
//            /*
//                如果直接使用：
//                return this.createVoucherOrder(voucherId);
//                其实拿到的是VoucherOrderServiceImpl这一个对象，而不是代理对象，事务失效。
//                而事务要生效，其实是Spring拿到了代理对象，并对其进行事务管理，
//                因此我们需要拿取对象的代理对象，并用代理对象调用方法，进而让Spring去代理。
//                为此，我们需要：
//                1.引入依赖
//                    <!-- 代理模式 -->
//                    <dependency>
//                        <groupId>org.aspectj</groupId>
//                        <artifactId>aspectjweaver</artifactId>
//                    </dependency>
//                2.启动类上加上如下注解：
//                    @EnableAspectJAutoProxy(exposeProxy = true)//暴露代理对象
//             */
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        }

        //利用redis分布式锁
//        SimpleRedisLock lock = new SimpleRedisLock("lock:order:" + userId, stringRedisTemplate);
        //获取锁
//        boolean isLock = lock.tryLock(5);

        //利用redisson
        RLock lock = redissonClient.getLock(RedisConstants.LOCK_ORDER_KEY + userId);
        boolean isLock = lock.tryLock();

        if(!isLock){
            return Result.fail("一个人只允许下一单！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 基于redis锁的秒杀
     *
     * 2. 创建订单
     *
     * @param voucherId
     * @return
     */
    @Transactional
    @Override
    public Result createVoucherOrder(Long voucherId) {
        //5.一人一单
        Long userId = UserHolder.getUser().getId();
        long count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherId)
                .count();

        if (count > 0) {
            return Result.fail("您已经购买");
        }

        //6.扣减库存
        boolean success = seckillVoucherService
                .lambdaUpdate()
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .gt(SeckillVoucher::getStock, 0)
                .update();
        if (!success) {
            return Result.fail("库存不足！");
        }

        //7.创建订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        this.save(voucherOrder);

        //7.返回订单id
        return Result.ok(orderId);
    }

    /**
     * 创建订单
     * @param voucherOrder
     */
    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        long count = lambdaQuery()
                .eq(VoucherOrder::getUserId, userId)
                .eq(VoucherOrder::getVoucherId, voucherId)
                .count();

        if (count > 0) {
            log.error("重复购买");
            return;
        }

        //6.扣减库存
        boolean success = seckillVoucherService
                .lambdaUpdate()
                .setSql("stock = stock - 1")
                .eq(SeckillVoucher::getVoucherId, voucherId)
                .gt(SeckillVoucher::getStock, 0)
                .update();
        if (!success) {
            log.error("库存不足");
        }

        //7.创建订单
        this.save(voucherOrder);
    }



    /**
     * 线程池
     */
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    /**
     * 初始化线程
     */
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandlerFromRedisStream());
    }

    /**
     * 提交订单
     * @param voucherOrder
     */
    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        log.error("提交订单");
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock(RedisConstants.LOCK_ORDER_KEY + userId);
        boolean isLock = lock.tryLock();

        if(!isLock){
            log.error("不允许重复下单");
            return;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 在不同线程下，Spring不能获取代理对象，因此需要在主线程提前获取
     */
    private IVoucherOrderService proxy;



    /**
     * 异步秒杀(基于JVM阻塞队列)
     *
     * 1. 预加载脚本
     *
     * @param voucherId
     * @return
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("lua/seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    /**
     * 异步秒杀(基于JVM阻塞队列)
     *
     * 阻塞队列
     */
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    /**
     * 异步秒杀(基于JVM阻塞队列)
     *
     * 2. 创建线程从阻塞队列获取任务
     *
     */
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    // 1.获取队列的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    // 2.处理订单
                    handleVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }
            }
        }
    }

    /**
     * 异步秒杀(基于JVM阻塞队列)
     *
     * 3. 主业务逻辑
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucherAsynchronousByJVM(Long voucherId) {
        Long userId = UserHolder.getUser().getId();

        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                RedisConstants.SECKILL_STOCK_KEY,
                RedisConstants.SECKILL_ORDER_KEY,
                voucherId.toString(),
                userId.toString()
        );

        // 2.判断结果是否为0
        int r = result.intValue();
        if(r != 0) {
            // 2.1异常
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 2.1成功，异步下单，把下单信息保存到阻塞队列
        long orderId = redisIdWorker.nextId(RedisConstants.INCR_ORDER);
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        orderTasks.add(voucherOrder);

        // 3.获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 4.返回订单id
        return Result.ok(orderId);
    }



    /**
     *  基于redis stream的异步秒杀
     *
     *  1. 预加载脚本
     *
     */
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT_STREAM;
    static {
        SECKILL_SCRIPT_STREAM = new DefaultRedisScript<>();
        SECKILL_SCRIPT_STREAM.setLocation(new ClassPathResource("lua/seckillStream.lua"));
        SECKILL_SCRIPT_STREAM.setResultType(Long.class);
    }

    /**
     * 基于redis stream的异步秒杀
     *
     * 2. 主业务逻辑
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVouvherAsynchronousByRedisStream(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId(RedisConstants.INCR_ORDER);
        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT_STREAM,
                Collections.emptyList(),
                RedisConstants.SECKILL_STOCK_KEY,
                RedisConstants.SECKILL_ORDER_KEY,
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        // 2.判断结果是否为0
        int r = result.intValue();
        if(r != 0) {
            // 2.1异常
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 3.获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();

        // 4.返回订单id
        return Result.ok(orderId);
    }

    /**
     * 获取redis stream的任务
     *
     * 3. 新线程来读取stream里的任务
     *
     */
    private class VoucherOrderHandlerFromRedisStream implements Runnable {
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true) {
                try {
                    // 1.获取队列的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    // 2.判断消息获取是否成功
                    if(list == null || list.isEmpty()) {
                        continue;
                    }

                    // 3. 解析订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values,new VoucherOrder(),true);

                    // 4. 处理订单
                    handleVoucherOrder(voucherOrder);

                    // 5.ACK确认 SACK stream.order g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());

                } catch (Exception e) {
                    log.error("处理redis stream[{}]订单异常",queueName,e);
                    //异常则处理PendingList的消息
                    handlePendingList();
                }
            }
        }

        /**
         * 异常处理
         */
        private void handlePendingList() {
            while (true) {
                try {
                    // 1.获取PendingList的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );

                    // 2.判断消息获取是否成功
                    if(list == null || list.isEmpty()) {
                        // 没读到说明PendingList没有异常消息
                        break;
                    }

                    // 3. 解析订单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> values = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(values,new VoucherOrder(),true);

                    // 4. 处理订单
                    handleVoucherOrder(voucherOrder);

                    // 5.ACK确认 SACK stream.order g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());

                } catch (Exception e) {
                    log.error("处理redis stream PendingList[{}]订单异常",queueName,e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }

    }
}